package ModelLayer;
import java.util.ArrayList;

/**
 * Write a description of class LoanRegister here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class LoanRegister
{
    // instance variables - replace the example below with your own
    private ArrayList<Loan> loan; // list of loans;
    private static LoanRegister instance;
    

    /**
     * Constructor for objects of class LoanRegister
     */
    private LoanRegister() //contructor
    {
        // initialise instance variables
        loan = new ArrayList<Loan>();
    }

    /**
     * An example of a method - replace this comment with your own
     * 
     * @param  y   a sample parameter for a method
     * @return     the sum of x and y 
     */
    public static LoanRegister getInstance() //calls the constructor if there is no list 
    {
        // put your code here
        if( null == instance )
        {
            instance = new LoanRegister();
            return instance;
        }
        return instance;
    }
    
    public void setLoan(int id, String borrowDate, int period,Copy copy, Person person) //creates a loan 
    {
        Loan loan1= new Loan(id, borrowDate, period, copy, person);
        loan.add(loan1);
        person.addLoan(loan1);
        copy.setLoan(loan1);

    }
    
    public ArrayList<Loan> getLoan() // gets list of loans
    {
        return loan;
    }
    
    public void deleteLoan(int id) // delete a loan by its ID
    {
        int index = loan.indexOf( findLoan(id) ) ;
        loan.remove(index);
    }
    
    public Loan findLoan(int id) //finds a loan by its ID
    {
        int index = 0;
        for(; index < loan.size(); index++)
        {
            if( loan.get(index).getId()==id )
            {
                return loan.get(index);
            }
        }
        return null;
    }
    
    public void editLoan(Loan loan, String borrowDate, int period) // edits a loan's borrowdate and perios
    {
      
      loan.setDate(borrowDate);
      loan.setPeriod(period);
    }
    
    public void deleteLoan(Loan loan1) //delete a loan
    {
        loan.remove(loan1);
    }
    
    
    
    public String printLoans() // returns a string with all the loans
    {
        String s="";
        int index=0;
        while(index<loan.size())
        {            
            s=loan.get(index).toString()+'\n';
            index++;
        }
        return s;
    }
}